<template>
  <div>
    <el-table
        height="550"
        max-height="550"
        border
        :data="topicItemList"
        :highlight-current-row="true"
    >
      <el-table-column label="题目编号" width="150" prop="id" show-overflow-tooltip align="center">

      </el-table-column>
      <el-table-column label="题目名称" width="200" prop="name" show-overflow-tooltip align="center">

      </el-table-column>
      <el-table-column label="题目选项" width="150" prop="optionList" show-overflow-tooltip align="center">
        <template slot-scope="scope">

          <el-popover trigger="hover" placement="top">
            <div v-for="(opinion,index) in scope.row.optionList" :key="index" style="text-align: center;">
              <p>{{ opinion.name }} : {{ opinion.value }}</p>

            </div>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">选项详情</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="正确答案" width="100" prop="correctAnswerItemName" show-overflow-tooltip align="center">

      </el-table-column>
      <el-table-column label="答对奖励" width="100" prop="award" show-overflow-tooltip align="center">

      </el-table-column>
      <el-table-column label="排序" width="100" prop="sort" show-overflow-tooltip align="center">

      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot="header" slot-scope="scope">
          <el-button size="mini" type="text" @click="showTopiceTime(scope.row,'add')">新增题目</el-button>
        </template>

        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showTopiceTime(scope.row,'update')">修改</el-button>
          <el-button :style="{'color': 'red'}" size="mini" type="text" @click="deleteTopiceTime(scope.row)">删除
          </el-button>

        </template>

      </el-table-column>
    </el-table>

    <el-drawer
        :title="drawer.title"
        :visible.sync="drawer.flag"
        size="50%"
        :wrapperClosable="false"
        :append-to-body="true"
        @close="$refs['topicItemRef'].resetFields();topicItem = {};optionItems = []"

    >
      <div class="drawer-main">

        <el-form :model="topicItem" label-width="80px" ref="topicItemRef" :rules="rules">
          <el-form-item label="题目名称" prop="name">
            <el-input v-model="topicItem.name"/>
          </el-form-item>

          <el-form-item label="选项集合" required>
            <el-button size="medium" @click="addDomain">新增选项</el-button>
            <div style="font-size: 12px;color: #999;">最多只能有5个选项，最少需要有2个选项</div>
          </el-form-item>
          <!-- <div >


          </div> -->
          <!-- <div style="display: flex;justify-content: center;">
                  <p style="font-size: 12px;color: #999;">最多只能有5个选项，最少需要有2个选项</p>
          </div > -->

          <el-form-item :label="`选项:${option.name}`" v-for="(option,index) in optionItems" :key="index"

                        style="margin-left: 20px;"
          >
            <el-input v-model="option.value" placeholder="选项内容" style="width: 300px;"/>
            <el-button size="medium" style="margin-left: 10px;" @click="removeDomain(option)"> 删除</el-button>
          </el-form-item>
          <el-form-item label="正确答案" prop="correctAnswerItemName">
            <el-select v-model="topicItem.correctAnswerItemName">

              <el-option :disabled="topicItem.correctAnswerItemName === option.name" :label="option.name"
                         :value="option.name" v-for="(option,index) in optionItems" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="答对奖励" prop="award">
            <el-input v-model="topicItem.award"/>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="topicItem.sort" placeholder/>
          </el-form-item>

        </el-form>


        <div class="drawer-btn">
          <el-button size="medium" type="primary" @click="saveOrupdate">确认提交</el-button>
          <el-button size="medium" @click="drawer.flag = false">取消</el-button>
        </div>
      </div>

    </el-drawer>

  </div>
</template>

<script>

import {rules} from '@/utils/rules';
import {buildOption, deepCopy} from '@/utils/common';
import {post, get} from '@/utils/api'

export default {


  data() {
    let chackSort = (rule, value, callback) => {
      if (!rules.zInteger.test(value)) {

        return callback('序号需要必须是正整数~');
      }

      return callback();
    }
    let chackAward = (rule, value, callback) => {
      if (!rules.zInteger.test(value)) {

        return callback('奖励值需要必须是正整数~');
      }

      return callback();
    }
    return {
      drawer: {
        title: '',
        flag: false
      },
      topicItem: {},
      optionItems: [],
      topicItemList: [],
      rules: {
        name: [
          {required: true, message: '题目名称不能为空', trigger: 'blur'}
        ],
        award: [
          {required: true, message: '答对奖励不能为空', trigger: 'blur'},
          {required: true, validator: chackAward, trigger: 'blur'}
        ],
        correctAnswerItemName: [
          {required: true, message: '题目正确答案不能为空', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '题目序号不能为空', trigger: 'blur'},
          {required: true, validator: chackSort, trigger: 'blur'}
        ]

      }

    }
  },
  props: {
    topic: {
      type: Object,
      default: {}
    }
  },
  methods: {
    showTopiceTime(row, env) {

      this.drawer.flag = true;
      switch (env) {
        case 'add':
          this.drawer.title = '新增题目';

          break;
        case 'update':
          this.drawer.title = '修改题目信息';
          this.$nextTick(() => {
            this.topicItem = deepCopy(row);
            this.optionItems = deepCopy(row.optionList);
          });
          break;
      }


    },
    deleteTopiceTime(row) {

      const promise = post({
        url: '/base-topic/back/test-topic-item/delete',
        data: {id: row.id}
      });

      promise.then(res => {
        if (res && res.code === 200) {

          this.getTopicItemList();
          this.$message.success(res.message);
          return;
        }
        this.$message.error(res.message);
      })


    },
    saveOrupdate() {
      this.$refs['topicItemRef'].validate(valid => {
        if (!this.optionItems || this.optionItems.length < 2) {
          this.$message.error('每道题目最少要有两个选项~');
          return;
        }
        if (!valid) {
          this.$message.error('表单数据校验失败,请检查');
          return;
        }
        this.topicItem.topicId = this.topic.id;
        this.topicItem.optionList = this.optionItems;
        const promise = post({
          url: '/base-topic/back/test-topic-item/save-or-update',
          data: {...this.topicItem}
        });
        promise.then(res => {
          if (res && res.code === 200) {
            this.getTopicItemList();
            this.drawer.flag = false;
            this.$message.success(res.message);
          }
        })
      });
    },
    addDomain() {
      if (this.optionItems && this.optionItems.length < 5) {
        //发送请求保存选项

        let option = buildOption(this.optionItems);

        if (option !== null) {

          this.optionItems.push(option);

        }

      } else {
        this.$message.error('最多只能添加5个选项~')
      }

    },
    removeDomain(option) {
      console.log('option', option.id)
      let index = this.optionItems.indexOf(option);
      if (index != -1) {
        //发起请求删除选项
        if (option.id !== undefined) {
          const promise = post({
            url: '/base-topic/back/test-topic-item-option/delete',
            data: {id: option.id}
          });

          promise.then(res => {
            if (res && res.code === 200) {

              this.optionItems.splice(index, 1);
              //删除成功
              this.getTopicItemList();
              this.$message.success(res.message);
            }
          })
        } else {
          this.optionItems.splice(index, 1);
        }

      }


    },
    getTopicItemList() {

      if (this.topic.id != null) {
        const promise = get({
          url: '/base-topic/back/test-topic-item/list',
          params: {topicId: this.topic.id}
        });

        promise.then(res => {
          if (res.code === 200) {
            console.log('topicItems', res.data);
            this.topicItemList = res.data;
          }
        })
      }


    }
  },
  mounted() {
    this.$nextTick(() => {
      console.log('topic', this.topic)
      this.getTopicItemList();
    })
  }

}
</script>

<style scoped>
.drawer-main {
  padding-left: 20px;
  padding-right: 20px;
  position: relative;
  padding-bottom: 50px;
}

.drawer-btn {
  position: fixed;
  bottom: 0;
  padding-bottom: 20px;
  background-color: #fff;
}

</style>